package edu.hit.irlab.coref.corpus;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import edu.hit.irlab.coref.CRConfigProperties;
import edu.hit.irlab.coref.corpus.converter.Converter;

/**
 * Main functions for dealing with the <i>Corpus</i>
 * @author chuter
 *
 */
public class Corpus {
	private static final String DOCNODETAG = "document";
	private static final String DOCID = "DOCID";
	private static final String CHARSET = "UTF8";
	private static final CRConfigProperties _conf = CRConfigProperties.getInstance(); 
	private static final String corpusPath = _conf.getTestCorpusPath();
	private static final Converter _corpus_Convt = CRConfigProperties.getInstance().getCorpusConverter();

	
	private Corpus () {}
	
	/** load the xml file 
	 * @throws DocumentException */
	public static Document loadCorpus(String filePath) throws DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File(filePath));
		return document;
	}
	
	/** get the text file path */
	public static String getDocPath(Document dom) {
		Element docNode = (Element) dom.selectSingleNode(DOCNODETAG);
		String doc_id = docNode.attributeValue(DOCID);
		return corpusPath+"/"+doc_id;
	}
	
	/** 
	 * Load document by giving the documentname and the original charset,
	 * and return the document in the default charset
	 * @throws IOException 
	 */
	public static String loaddocument(String documentname, 
							   String oldCharset) throws IOException {
		InputStreamReader read = new InputStreamReader (
									new FileInputStream(documentname), oldCharset);
		BufferedReader input = new BufferedReader(read);
		StringBuffer buffer = new StringBuffer();
		String strtemp = input.readLine();
		
		while (strtemp != null) {
			buffer.append(strtemp+"\n");
			strtemp = input.readLine();
		}
		read.close();
		input.close();
		
		return buffer.toString();
	}
	
	/** Get the corresponding text content of one corpus file.<br> 
	 *  Use the corresponding <i>Corpus Converter</i> to get it 
	 * @throws IOException */
	public static String getTextCont(Document dom) {
		if (_corpus_Convt == null) {
			System.err.println("You must config the corpus converter first!");
			System.exit(1);
		}
		
		String copusDocpath = _conf.getCorpusDocPath();
		return _corpus_Convt.getDocumentString(dom, copusDocpath);
	}
	
	//test program
	public static void main(String[] argv) throws IOException, DocumentException {
		String textfile = "e:/ll/result18.xml";
		String cont = Corpus.getTextCont(Corpus.loadCorpus(textfile));
		System.out.println(cont);
		System.out.println(cont.substring(111, 113));
	}
}
